// pages/index/index.js
const { createCalculator } = require("../../dist/js/index.cjs.js");

Page({
  data: {
    num1: 10,
    num2: 20,
    result: null,
    operation: "",
    calculator: null,
  },

  async onLoad() {
    wx.showLoading({
      title: "加载中...",
    });

    try {
      // 创建计算器实例（小程序需要使用绝对路径）
      const calculator = await createCalculator("/dist/wasm/add.wasm");
      this.setData({ calculator });
      console.log("✅ 计算器初始化成功");
      wx.hideLoading();
      wx.showToast({
        title: "初始化成功",
        icon: "success",
      });
    } catch (err) {
      console.error("初始化失败:", err);
      wx.hideLoading();
      wx.showToast({
        title: "初始化失败",
        icon: "error",
      });
    }
  },

  onNum1Input(e) {
    this.setData({
      num1: parseFloat(e.detail.value) || 0,
    });
  },

  onNum2Input(e) {
    this.setData({
      num2: parseFloat(e.detail.value) || 0,
    });
  },

  async onAdd() {
    if (!this.data.calculator) {
      wx.showToast({ title: "计算器未初始化", icon: "error" });
      return;
    }

    wx.showLoading({ title: "计算中..." });
    try {
      const result = await this.data.calculator.add(this.data.num1, this.data.num2);
      this.setData({
        result,
        operation: "加法 (add)",
      });
      wx.hideLoading();
    } catch (err) {
      console.error("计算失败:", err);
      wx.hideLoading();
      wx.showToast({ title: "计算失败", icon: "error" });
    }
  },

  async onMultiply() {
    if (!this.data.calculator) {
      wx.showToast({ title: "计算器未初始化", icon: "error" });
      return;
    }

    wx.showLoading({ title: "计算中..." });
    try {
      const result = await this.data.calculator.multiply(this.data.num1, this.data.num2);
      this.setData({
        result,
        operation: "乘法 (multiply)",
      });
      wx.hideLoading();
    } catch (err) {
      console.error("计算失败:", err);
      wx.hideLoading();
      wx.showToast({ title: "计算失败", icon: "error" });
    }
  },
});
